import React, { useState, useEffect } from 'react';
import {
  Table, Button, Space, Modal, Form, Input, Select, Switch, message,
  Card, Row, Col, Typography, Tag, Popconfirm, Drawer, List, Divider
} from 'antd';
import {
  PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined,
  CopyOutlined, SendOutlined, SettingOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  notificationService,
  NotificationTemplate,
  TemplateVariable,
  NotificationItem
} from '@/services/notificationService';

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;

interface NotificationTemplatesProps {
  visible: boolean;
  onClose: () => void;
}

interface TemplateState {
  templates: NotificationTemplate[];
  loading: boolean;
  editingTemplate: NotificationTemplate | null;
  modalVisible: boolean;
  previewVisible: boolean;
  testVisible: boolean;
  selectedTemplate: NotificationTemplate | null;
  pagination: {
    current: number;
    pageSize: number;
    total: number;
  };
}

export default function NotificationTemplates({
  visible,
  onClose
}: NotificationTemplatesProps) {
  const [state, setState] = useState<TemplateState>({
    templates: [],
    loading: false,
    editingTemplate: null,
    modalVisible: false,
    previewVisible: false,
    testVisible: false,
    selectedTemplate: null,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0
    }
  });

  const [form] = Form.useForm();
  const [testForm] = Form.useForm();

  // 加载模板列表
  const loadTemplates = async () => {
    setState(prev => ({ ...prev, loading: true }));
    
    try {
      const response = await notificationService.getTemplates({
        page: state.pagination.current - 1,
        size: state.pagination.pageSize
      });
      
      setState(prev => ({
        ...prev,
        templates: response.content,
        pagination: {
          ...prev.pagination,
          total: response.totalElements
        },
        loading: false
      }));
    } catch (error: any) {
      console.error('加载模板失败:', error);
      message.error('加载模板失败');
      setState(prev => ({ ...prev, loading: false }));
    }
  };

  // 初始化
  useEffect(() => {
    if (visible) {
      loadTemplates();
    }
  }, [visible]);

  // 创建/编辑模板
  const handleSaveTemplate = async (values: any) => {
    try {
      const templateData = {
        ...values,
        variables: values.variables || []
      };

      if (state.editingTemplate) {
        await notificationService.updateTemplate(state.editingTemplate.id, templateData);
        message.success('模板更新成功');
      } else {
        await notificationService.createTemplate(templateData);
        message.success('模板创建成功');
      }

      setState(prev => ({
        ...prev,
        modalVisible: false,
        editingTemplate: null
      }));
      form.resetFields();
      loadTemplates();
    } catch (error: any) {
      console.error('保存模板失败:', error);
      message.error('保存模板失败');
    }
  };

  // 删除模板
  const handleDeleteTemplate = async (id: string) => {
    try {
      await notificationService.deleteTemplate(id);
      message.success('模板删除成功');
      loadTemplates();
    } catch (error: any) {
      console.error('删除模板失败:', error);
      message.error('删除模板失败');
    }
  };

  // 复制模板
  const handleCopyTemplate = (template: NotificationTemplate) => {
    const newTemplate = {
      ...template,
      name: `${template.name} (副本)`,
      id: undefined,
      createdBy: undefined,
      createdByName: undefined,
      createdAt: undefined,
      updatedAt: undefined
    };
    
    setState(prev => ({
      ...prev,
      editingTemplate: newTemplate as NotificationTemplate,
      modalVisible: true
    }));
    
    form.setFieldsValue(newTemplate);
  };

  // 测试模板
  const handleTestTemplate = async (values: any) => {
    try {
      if (!state.selectedTemplate) return;
      
      await notificationService.testNotification({
        type: values.channel,
        recipient: values.recipient,
        templateId: state.selectedTemplate.id,
        variables: values.variables || {}
      });
      
      message.success('测试通知发送成功');
      setState(prev => ({ ...prev, testVisible: false }));
      testForm.resetFields();
    } catch (error: any) {
      console.error('测试通知失败:', error);
      message.error('测试通知失败');
    }
  };

  // 预览模板
  const previewTemplate = (template: NotificationTemplate) => {
    setState(prev => ({
      ...prev,
      selectedTemplate: template,
      previewVisible: true
    }));
  };

  // 表格列定义
  const columns: ColumnsType<NotificationTemplate> = [
    {
      title: '模板名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: NotificationTemplate) => (
        <Space>
          <span>{text}</span>
          {!record.isActive && <Tag color="red">已禁用</Tag>}
        </Space>
      )
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category: string) => <Tag>{category}</Tag>
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: NotificationItem['type']) => {
        const colors = {
          info: 'blue',
          success: 'green',
          warning: 'orange',
          error: 'red',
          system: 'purple'
        };
        return <Tag color={colors[type]}>{type}</Tag>;
      }
    },
    {
      title: '支持渠道',
      dataIndex: 'channels',
      key: 'channels',
      render: (channels: string[]) => (
        <Space>
          {channels.map(channel => (
            <Tag key={channel}>{channel}</Tag>
          ))}
        </Space>
      )
    },
    {
      title: '创建者',
      dataIndex: 'createdByName',
      key: 'createdBy'
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleDateString()
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record: NotificationTemplate) => (
        <Space>
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => previewTemplate(record)}
          />
          <Button
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={() => {
              setState(prev => ({
                ...prev,
                editingTemplate: record,
                modalVisible: true
              }));
              form.setFieldsValue(record);
            }}
          />
          <Button
            type="text"
            size="small"
            icon={<CopyOutlined />}
            onClick={() => handleCopyTemplate(record)}
          />
          <Button
            type="text"
            size="small"
            icon={<SendOutlined />}
            onClick={() => {
              setState(prev => ({
                ...prev,
                selectedTemplate: record,
                testVisible: true
              }));
            }}
          />
          <Popconfirm
            title="确定要删除这个模板吗？"
            onConfirm={() => handleDeleteTemplate(record.id)}
          >
            <Button
              type="text"
              size="small"
              icon={<DeleteOutlined />}
              danger
            />
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <>
      <Drawer
        title="通知模板管理"
        placement="right"
        width={1000}
        open={visible}
        onClose={onClose}
        extra={
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setState(prev => ({
                ...prev,
                editingTemplate: null,
                modalVisible: true
              }));
              form.resetFields();
            }}
          >
            新建模板
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={state.templates}
          loading={state.loading}
          rowKey="id"
          pagination={{
            current: state.pagination.current,
            pageSize: state.pagination.pageSize,
            total: state.pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            onChange: (page, pageSize) => {
              setState(prev => ({
                ...prev,
                pagination: { ...prev.pagination, current: page, pageSize: pageSize || 10 }
              }));
              loadTemplates();
            }
          }}
        />
      </Drawer>

      {/* 创建/编辑模板模态框 */}
      <Modal
        title={state.editingTemplate ? '编辑模板' : '新建模板'}
        open={state.modalVisible}
        onCancel={() => {
          setState(prev => ({
            ...prev,
            modalVisible: false,
            editingTemplate: null
          }));
          form.resetFields();
        }}
        onOk={() => form.submit()}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSaveTemplate}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="模板名称"
                rules={[{ required: true, message: '请输入模板名称' }]}
              >
                <Input placeholder="请输入模板名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="category"
                label="分类"
                rules={[{ required: true, message: '请输入分类' }]}
              >
                <Input placeholder="请输入分类" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="type"
                label="通知类型"
                rules={[{ required: true, message: '请选择通知类型' }]}
              >
                <Select placeholder="请选择通知类型">
                  <Option value="info">信息</Option>
                  <Option value="success">成功</Option>
                  <Option value="warning">警告</Option>
                  <Option value="error">错误</Option>
                  <Option value="system">系统</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="channels"
                label="支持渠道"
                rules={[{ required: true, message: '请选择支持渠道' }]}
              >
                <Select mode="multiple" placeholder="请选择支持渠道">
                  <Option value="in_app">站内通知</Option>
                  <Option value="email">邮件</Option>
                  <Option value="sms">短信</Option>
                  <Option value="push">推送</Option>
                  <Option value="webhook">Webhook</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="subject"
            label="主题"
            rules={[{ required: true, message: '请输入主题' }]}
          >
            <Input placeholder="请输入主题" />
          </Form.Item>

          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: '请输入内容' }]}
          >
            <TextArea
              rows={6}
              placeholder="请输入内容，支持变量：{{variableName}}"
            />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <TextArea rows={3} placeholder="请输入模板描述" />
          </Form.Item>

          <Form.Item
            name="isActive"
            label="启用状态"
            valuePropName="checked"
            initialValue={true}
          >
            <Switch />
          </Form.Item>
        </Form>
      </Modal>

      {/* 模板预览模态框 */}
      <Modal
        title="模板预览"
        open={state.previewVisible}
        onCancel={() => setState(prev => ({ ...prev, previewVisible: false }))}
        footer={[
          <Button key="close" onClick={() => setState(prev => ({ ...prev, previewVisible: false }))}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {state.selectedTemplate && (
          <div>
            <Card size="small" style={{ marginBottom: 16 }}>
              <Row gutter={16}>
                <Col span={8}>
                  <Text strong>模板名称：</Text>
                  <div>{state.selectedTemplate.name}</div>
                </Col>
                <Col span={8}>
                  <Text strong>分类：</Text>
                  <div><Tag>{state.selectedTemplate.category}</Tag></div>
                </Col>
                <Col span={8}>
                  <Text strong>类型：</Text>
                  <div><Tag color="blue">{state.selectedTemplate.type}</Tag></div>
                </Col>
              </Row>
            </Card>

            <Card size="small" style={{ marginBottom: 16 }}>
              <Text strong>支持渠道：</Text>
              <div style={{ marginTop: 8 }}>
                <Space>
                  {state.selectedTemplate.channels.map(channel => (
                    <Tag key={channel}>{channel}</Tag>
                  ))}
                </Space>
              </div>
            </Card>

            <Card size="small" style={{ marginBottom: 16 }}>
              <Text strong>主题：</Text>
              <div style={{ marginTop: 8, padding: 8, backgroundColor: '#f5f5f5', borderRadius: 4 }}>
                {state.selectedTemplate.subject}
              </div>
            </Card>

            <Card size="small" style={{ marginBottom: 16 }}>
              <Text strong>内容：</Text>
              <div style={{ marginTop: 8, padding: 8, backgroundColor: '#f5f5f5', borderRadius: 4, whiteSpace: 'pre-wrap' }}>
                {state.selectedTemplate.content}
              </div>
            </Card>

            {state.selectedTemplate.variables.length > 0 && (
              <Card size="small">
                <Text strong>变量列表：</Text>
                <List
                  size="small"
                  dataSource={state.selectedTemplate.variables}
                  renderItem={(variable: TemplateVariable) => (
                    <List.Item>
                      <Space>
                        <Tag color="blue">{variable.name}</Tag>
                        <Text type="secondary">{variable.type}</Text>
                        <Text>{variable.description}</Text>
                        {variable.required && <Tag color="red">必需</Tag>}
                      </Space>
                    </List.Item>
                  )}
                />
              </Card>
            )}
          </div>
        )}
      </Modal>

      {/* 测试模板模态框 */}
      <Modal
        title="测试模板"
        open={state.testVisible}
        onCancel={() => {
          setState(prev => ({ ...prev, testVisible: false }));
          testForm.resetFields();
        }}
        onOk={() => testForm.submit()}
      >
        <Form
          form={testForm}
          layout="vertical"
          onFinish={handleTestTemplate}
        >
          <Form.Item
            name="channel"
            label="发送渠道"
            rules={[{ required: true, message: '请选择发送渠道' }]}
          >
            <Select placeholder="请选择发送渠道">
              {state.selectedTemplate?.channels.map(channel => (
                <Option key={channel} value={channel}>{channel}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="recipient"
            label="接收者"
            rules={[{ required: true, message: '请输入接收者' }]}
          >
            <Input placeholder="请输入邮箱地址或用户ID" />
          </Form.Item>

          {state.selectedTemplate?.variables.length > 0 && (
            <Form.Item label="变量值">
              {state.selectedTemplate.variables.map((variable: TemplateVariable) => (
                <Form.Item
                  key={variable.name}
                  name={['variables', variable.name]}
                  label={`${variable.name} (${variable.description})`}
                  rules={variable.required ? [{ required: true, message: `请输入${variable.name}` }] : []}
                >
                  <Input placeholder={variable.example || `请输入${variable.name}`} />
                </Form.Item>
              ))}
            </Form.Item>
          )}
        </Form>
      </Modal>
    </>
  );
}

// 导出类型
export type { NotificationTemplatesProps };